package com.gz.logistics.app;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.gz.logistics.R;
import com.gz.logistics.adapter.OutingAssembleDetailAdapter;
import com.gz.logistics.library.IAuthor;
import com.gz.logistics.library.IOrder;
import com.gz.logistics.library.listener.GetAssembleDetailListener;
import com.gz.logistics.library.listener.SingleOrderLoggisticsStatusChangeListener;
import com.gz.logistics.library.pojo.OrderInfo;
import com.gz.logistics.library.pojo.UserInfo;
import com.gz.logistics.library.util.Constants;
import com.gz.logistics.library.util.PreferenceModel;
import com.gz.logistics.util.ToastUtils;
import com.gz.logistics.widget.LoadingCover;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * author wanner1991
 */
public class OutingAssembleDetailActivity extends BaseActivity implements LoadingCover.OnLoadingCoverRefreshListener,
        View.OnClickListener,PullToRefreshBase.OnRefreshListener, OutingAssembleDetailAdapter.OnClickSignLogisticsBtnListener {
    private String TAG = OutingAssembleDetailActivity.class.getSimpleName();
    private UserInfo userInfo;
    private int storage_out_id;// 该预出库单id
    private ImageView iv_action_back;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;

    private MyGetAssembleDetailListener myGetAssembleDetailListener ;
    private List<OrderInfo> mDataList;
    private OutingAssembleDetailAdapter mAdapter;

    private PullToRefreshListView mPullListView;
    private LoadingCover mLoadingCover;
    private Dialog mLoadingData;
    private boolean isChaged = false;// 标记该订单的转状态是否改变，如果改变了，返回之前页面后刷新界面，没改变则不

    private MySingleOrderLoggisticsStatusChangeListener mSingleOrderLoggisticsStatusChangeListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_assemble_detail);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        mActionBar.setCustomView(R.layout.common_head_layout);//自定义ActionBar布局
        userInfo =  IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        storage_out_id = this.getIntent().getIntExtra("storage_out_id", -1);
        initView();
        initListener();
        initDate();
        onLoadingCoverRefresh();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myGetAssembleDetailListener.release();
        mSingleOrderLoggisticsStatusChangeListener.release();

    }

    @Override
    public void onLoadingCoverRefresh() {
        IOrder.getInstance().getAssembleDetail(storage_out_id, myGetAssembleDetailListener);
    }

    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        IOrder.getInstance().getAssembleDetail(storage_out_id, myGetAssembleDetailListener);
    }



    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_actionbar_up:
                if (isChaged){
                    Intent intent = getIntent();
                    intent.putExtra("isChanged",true);
                    setResult(Define.ACTIVITY_CODE_ASSEMBLE_DETAI_CHANGE,intent);
                }
                isChaged = false;
                finish();
                break;
        }

    }
    /**
     * 如果店家物理返回按钮返回上一个页面， 对是否设置返回值进行判断设置
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isChaged){
                Intent intent = getIntent();
                intent.putExtra("isChanged",true);
                setResult(Define.ACTIVITY_CODE_ASSEMBLE_DETAI_CHANGE,intent);
            }
            isChaged = false;
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initView() {
        mPullListView = (PullToRefreshListView) this.findViewById(R.id.list);
        mLoadingCover = (LoadingCover) this.findViewById(R.id.layout_loading_cover);
        iv_action_back = (ImageView) this.findViewById(R.id.iv_actionbar_up);
        tv_actionbar_title = (TextView) this.findViewById(R.id.tv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) this.findViewById(R.id.tv_actionbar_deliveryName);


        mLoadingData = new Dialog(this,R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);
    }

    private void initListener() {
        mLoadingCover.setOnLoadingCoverRefreshListener(this);
        iv_action_back.setOnClickListener(this);
        myGetAssembleDetailListener = new MyGetAssembleDetailListener(this);
        mPullListView.setOnRefreshListener(this);
        mSingleOrderLoggisticsStatusChangeListener = new MySingleOrderLoggisticsStatusChangeListener(this);

    }

    private void initDate(){
        tv_actionbar_title.setText("预出库单详情");
        if (userInfo != null){
            tv_actionbar_deliveryName.setText("配送员："+userInfo.getUser_name());
        }

        mDataList = new ArrayList<OrderInfo>();
        mAdapter = new OutingAssembleDetailAdapter(this,mDataList,this);
        mPullListView.setAdapter(mAdapter);
    }

    /**
     * 点击每个订单里的“物流签收” 触发该方法
     * @param clickOrder
     */
    @Override
    public void onClickSignLogisticsBtn(OrderInfo clickOrder) {
        if (clickOrder != null){
            if (!isChaged){  // 订单状态发生改变，则把该订单编号返回给之前的界面
                isChaged = true;
            }
            mLoadingData.show();
            IOrder.getInstance().singalorderLogisticsStatusSign(clickOrder.getSn(),mSingleOrderLoggisticsStatusChangeListener);
        }

    }


    /**
     * 获取预出库单详情回调接口
     */
    public class MyGetAssembleDetailListener extends GetAssembleDetailListener{
        private OutingAssembleDetailActivity mOuter;

        public MyGetAssembleDetailListener(OutingAssembleDetailActivity mOuter) {
            this.mOuter = mOuter;
        }
        public void release(){
            new WeakReference<OutingAssembleDetailActivity>(mOuter);
        }

        @Override
        public void onNoNetWork() {
            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
            ToastUtils.showToast(mOuter, Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {

            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.mLoadingCover.onRefreshFailed();
            ToastUtils.showToast(mOuter,"加载失败");

        }

        @Override
        public void onResponseSuccess(List<OrderInfo> infos) {
            mDataList.clear();
            mDataList.addAll(infos);
            mAdapter.notifyDataSetChanged();
            mLoadingCover.onRefreshSuccess();

            if (mPullListView.isRefreshing()) {
                mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mLoadingData.isShowing()) {
                mLoadingData.dismiss();
            }


        }

        @Override
        public void onThisAssembleIsDiscarded() {
            mLoadingCover.onRefreshSuccess();

            if (mPullListView.isRefreshing()) {
                mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mLoadingData.isShowing()) {
                mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter,"该预出库记录已经作废");

        }

        @Override
        public void onOrdersInThisAssembleIsDiscards() {
            mLoadingCover.onRefreshSuccess();

            if (mPullListView.isRefreshing()) {
                mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mLoadingData.isShowing()) {
                mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter,"该预出库记录里所有订单都已作废");

        }

        @Override
        public void onThisAssembleNotRelativeWithTheUser() {
            mLoadingCover.onRefreshSuccess();

            if (mPullListView.isRefreshing()) {
                mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mLoadingData.isShowing()) {
                mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter,"该预出库记录里没有当前用户的订单");

        }
    }


    /**
     * 单订单物流签收 回调接口
     */
    private static class MySingleOrderLoggisticsStatusChangeListener extends SingleOrderLoggisticsStatusChangeListener {
        private OutingAssembleDetailActivity mOuter;

        public MySingleOrderLoggisticsStatusChangeListener(OutingAssembleDetailActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<OutingAssembleDetailActivity>(mOuter);
        }

        @Override
        public void onResponseSuccess() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(), "物流签收成功");
            mOuter.onLoadingCoverRefresh();
        }

        @Override
        public void onNoNetWork() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(),Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(),"物流签收失败");
        }
    }

}
